<script setup lang="ts">
import { reactive, onMounted, ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { saveGroupMenus, getGroupAuthInfo } from '@/api/system/authority'
import { ElMessage } from 'element-plus'
import { Check, Close, CircleCheck, Switch } from '@element-plus/icons-vue'
import { useLocaleStoreWithOut } from '@/store/modules/locale'
import { useCache } from '@/hooks/web/useCache'
import { useI18n } from '@/hooks/web/useI18n'

defineOptions({
  name: 'Authorization'
})

const { push } = useRouter()
const localeStore = useLocaleStoreWithOut()
const { wsCache } = useCache()
const { t } = useI18n()

//当前语言
const curLang = localeStore.getCurrentLocale.lang
const state = reactive({
  curGroup: {},
  menus: []
  // activeName: ''
})

const loading = ref(false)

onMounted(async () => {
  init()
})

// 保存授权
const save = async () => {
  loading.value = true
  //构建提交数据
  let auth = [] as any
  for (const obj of state.menus) {
    const menu = obj as any
    //没选中的菜单忽略
    if (!menu.checked) {
      continue
    }
    const hasElement = hasElements(menu)
    auth.push({ menuId: menu.menuId, hasElement: hasElement, elements: menu.curElements })
  }
  const data = { groupId: state.curGroup.groupId, auth: auth }
  await saveGroupMenus(data).then((res) => {
    const result = res as any
    //保存成功
    if (result.success) {
      ElMessage.success(t('group.saveSuccess'))
      // ElMessageBox.alert('保存成功')
    } else {
      ElMessage.error(t(result.message))
      // ElMessageBox.alert(result.message)
    }
    loading.value = false
  })
}
/**
 * 判断菜单是否有按钮权限
 * @param menu  菜单
 */
const hasElements = (menu: any) => {
  if (menu.pageElements && menu.pageElements.length > 0) {
    return 1
  }
  return 0
}
/**
 * 获取元素的key组成数组
 * @param elements 元素
 */
const getAllElementKeys = (elements: any) => {
  let arr = [] as any
  for (const element of elements) {
    arr.push(element.elementKey)
  }
  return arr
}

// 返回列表
const goBack = () => {
  push({ name: 'GroupList' })
}

//渲染页面的接口
const init = async () => {
  state.curGroup = wsCache.get('curGroup')
  const groupId = state.curGroup.groupId
  //修改
  if (groupId) {
    const data = (await getGroupAuthInfo(groupId)) as any
    let menus = data.data as any
    state.menus = menus

    await nextTick()
    // state.activeName = f(menus[0])
  }
}
/**
 * @description 全选
 * @author Elwin ZHANG
 * @date 2022-06-22 13:36
 */
const selectAll = () => {
  for (const obj of state.menus) {
    let menu = obj as any
    menu.checked = true
    if (hasElements(menu)) {
      menu.curElements = getAllElementKeys(menu.pageElements)
    }
  }
}

/**
 * @description 反选
 * @author Elwin ZHANG
 * @date 2022-06-22 13:36
 */
const reverse = () => {
  for (const obj of state.menus) {
    let menu = obj as any
    menu.checked = !menu.checked
    if (hasElements(menu)) {
      menu.curElements = reverseElementKeys(menu.pageElements, menu.curElements)
    }
  }
}

/**
 * 获取元素的key组成数组
 * @param elements 元素
 */
const reverseElementKeys = (elements: any, keys: any) => {
  let arr = [] as any
  const selectedKeys = keys as string[]
  for (const element of elements) {
    const key = element.elementKey as string
    if (!selectedKeys.includes(key)) {
      arr.push(key)
    }
  }
  return arr
}

/**
 * @description 显示菜单名
 * @param menu 菜单对象
 * @author Elwin ZHANG
 * @date 2022-06-17 17:30
 */
const getMenuName = (menu) => {
  // 默认是中文简体
  let name = menu.menuName
  //多语言判断
  if (curLang == 'en') {
    // 英文
    name = menu.enName
  } else if (curLang == 'zh_HK') {
    name = menu.hkName
  }
  //层级缩进
  if (menu.pageLevel == 1) {
    return name
  }
  if (menu.pageLevel == 2) {
    return '　　' + name
  }
  return '　　　　' + name
}
</script>

<template>
  <!-- <div> -->
  <!-- 卡片表頭 -->
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>【{{ state.curGroup.groupName }}】 {{ $t('group.authorization') }}</span>
        <div class="footer">
          <el-button type="success" plain @click="selectAll" :icon="CircleCheck">{{
            $t('group.all')
          }}</el-button>
          <el-button
            type="warning"
            plain
            @click="reverse"
            :icon="Switch"
            style="margin-left: 20px"
            >{{ $t('group.reverse') }}</el-button
          >
          <el-button
            type="primary"
            plain
            @click="save"
            :loading="loading"
            :icon="Check"
            style="margin-left: 20px"
            >{{ $t('common.save') }}</el-button
          >
          <el-button type="info" plain @click="goBack" :icon="Close" style="margin-left: 20px">{{
            $t('common.back')
          }}</el-button>
        </div>
      </div>
    </template>
    <!-- 部分checkbox選擇功能未實現 -->
    <el-form class="demo-form-inline" label-position="left">
      <el-row style="background-color: #ecf5ff; color: #409eff">
        <el-col :span="5"
          ><label>{{ $t('common.menu') }}</label></el-col
        >
        <el-col :span="3"
          ><label
            ><el-checkbox class="special" style="margin-left: -1px" />&nbsp;&nbsp;{{
              $t('group.visible')
            }}</label
          ></el-col
        >
        <el-col :span="16" style="margin-left: -1px">
          <el-checkbox-group>
            <el-checkbox style="width: 10%" />
            <el-checkbox style="width: 10%; margin-left: -1px" />
            <el-checkbox style="width: 10%; margin-left: -1px" />
            <el-checkbox style="width: 10%" />
          </el-checkbox-group>
        </el-col>
      </el-row>
    </el-form>
    <el-form
      :model="state.menus"
      class="demo-form-inline"
      label-position="left"
      style="max-height: 64vh; overflow-y: auto"
    >
      <el-row v-for="menu in state.menus" :key="menu.menuId">
        <el-col :span="5"
          ><label style="line-height: 32px">{{ getMenuName(menu) }}</label></el-col
        >
        <el-col :span="3"><el-checkbox v-model="menu.checked" /></el-col>
        <el-col :span="16">
          <el-checkbox-group v-model="menu.curElements">
            <el-checkbox
              v-for="ele in menu.pageElements"
              :key="ele.elementKey"
              :label="ele.elementKey"
              style="width: 10%"
              >{{
                curLang == 'en' ? ele.enName : curLang == 'zh_CN' ? ele.elementName : ele.hkName
              }}
            </el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>
<style lang="less" scoped>
.box-card {
  padding-left: 50px;
  padding-right: 50px;
  .card-header {
    font-size: medium;
    font-weight: bold;
    margin-bottom: -15px;
    letter-spacing: 2px;
  }
}
:deep(.el-col) {
  vertical-align: middle;
  line-height: 20px;
}
:deep(label, span) {
  line-height: 20px;
  font-size: 12px;
  line-height: 32px;
}

.footer {
  text-align: right;
  margin-top: -30px;
  margin-bottom: 10px;
  // margin-top: 50px;
}
// 二級菜單操作選項
.pageFunction {
  display: flex;
  flex-direction: row;
  margin-left: 1rem;
  font-size: 12px;
}
.pageFunction div {
  margin-left: 1rem;
}
// 按鈕樣式
:deep(.el-checkbox-button:last-child .el-checkbox-button__inner) {
  border-radius: 3px;
}
:deep(.normal_label .el-form-item__error) {
  left: 0px;
}

:deep(.normal_label .el-form-item__error) {
  left: 0px;
}

.el-tab-pane {
  margin-left: 50px;
}
:deep(.el-tabs--left .el-tabs__item.is-left) {
  text-align: left;
}
.special {
  vertical-align: middle;
}
// 滾動條
:deep(::-webkit-scrollbar) {
  opacity: 0.3;
  width: 6px;
  color: #ffffff;
}
:deep(::-webkit-scrollbar-thumb) {
  opacity: 0.5;
  border-radius: 4px;
  background-color: lightgray;
}
</style>
